<template>
  <div class="app-container">
    <el-button type="primary" @click="handleCreate" class="zdy-btn zdy-btn-rent">创建链接
      <img class="lines-img" src="@/assets/img/yunji-jiant.png" alt="">
    </el-button>
    <!-- <el-button type="primary" icon="el-icon-plus" @click="test" class="zdy-btn zdy-btn-rent">测试导出
    </el-button> -->
    <el-form :model="formData" ref="formDataForm" :inline="true" class="search-form-new" label-width="68px">
      <el-form-item label="链接名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入链接名称" clearable size="small" />
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="formData.state" placeholder="请选择状态" clearable size="small">
          <el-option label="启用" value="1" />
          <el-option label="停用" value="2" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleSearch">
          搜索
        </el-button>
        <!-- <el-button type="warning" icon="el-icon-refresh" size="small" @click="handleReset">
                    重置
                </el-button> -->
      </el-form-item>

    </el-form>
    <div class="table_box table_box_new">
      <el-table v-loading="loading" :data="cardSecretList" border style="width: 100%">
        <el-table-column prop="id" label="id" width="80" />
        <el-table-column v-if="checkPermi(['searchTenantID'])" prop="tenantId" label="店铺ID" width="80" />
        <el-table-column v-if="checkPermi(['searchTenantID'])" prop="tenantName" label="店铺名称" width="140" />

        <el-table-column prop="name" label="链接名称" />
        <el-table-column prop="randomStr" label="Key" width="160" />

        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>
        <el-table-column prop="expireTime" label="状态" width="180">
          <template slot-scope="scope">
            <el-tag type="danger" v-if="scope.row.state==2">停用</el-tag>
            <el-tag v-else>启用</el-tag>

          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="createXuanhao(scope.row)">
              查看链接
            </el-button>
            <!-- 
                        <el-button v-if="!isTimeExpired(scope.row.expireTime, true)" size="mini" type="primary"
                            @click="handleInvalidate(scope.row)">
                            立即失效
                        </el-button> -->
            <el-button size="mini" type="warning" @click="handleEditdate(scope.row)">
              修改
            </el-button>
            <!-- <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
                            删除
                        </el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="formData.pageNum" :limit.sync="formData.pageSize" @pagination="getList" />
      <!-- 创建卡密弹窗 -->
      <card-secret-modal :visible.sync="dialogVisible" @success="getList" ref="cardSecretModal" />
    </div>

    <el-dialog title="回收链接" :visible.sync="qrCodeShow" width="620px">
      <div v-if="qrCodeShow" ref="qrcode" style="width:200px; height:200px;margin:0 auto;margin-bottom:15px">
      </div>
      <div class="link-box">
        <div class="" style="text-align: center;">
          <span class="mylink"> <a :href="phoneLink" target="_blank">{{ phoneLink }}</a></span>
          <el-button type="primary" size="mini" @click="copy(phoneLink)">复制</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import QRCode from "qrcodejs2";
import cardSecretApi from "@/api/tenantApis/cardSecret";
import Pagination from "@/components/Pagination/index.vue";
import CardSecretModal from "./addLink.vue";
import dianshangHuishouApi from "@/api/tenantApis/dianshangHuishou";

// import ExcelJS from "exceljs";
export default {
  computed: {
    shopInfo() {
      return this.$store.getters.shopInfo;
    },
    retailDomain() {
      return this.$store.getters.retailDomain;
    },
  },
  name: "DianshangHuishou",
  components: { Pagination, CardSecretModal },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      cardSecretList: [],
      formData: {
        pageNum: 1,
        pageSize: 10,
      },
      // 弹窗显示状态
      dialogVisible: false,
      qrCodeShow: false,
      qrcode: null,
      phoneLink: "",
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async test() {
      // 创建工作簿
      const workbook = new ExcelJS.Workbook();

      // 添加工作表
      const worksheet = workbook.addWorksheet("员工信息");

      // 添加表头
      worksheet.columns = [
        { header: "姓名", key: "name", width: 15 },
        { header: "年龄", key: "age", width: 10 },
        { header: "城市", key: "city", width: 15 },
        { header: "部门", key: "department", width: 15 },
      ];

      // 添加数据
      worksheet.addRow({
        name: "张三",
        age: 25,
        city: "北京",
        department: "技术部",
      });
      worksheet.addRow({
        name: "李四",
        age: 30,
        city: "上海",
        department: "销售部",
      });
      worksheet.addRow({
        name: "王五",
        age: 28,
        city: "广州",
        department: "市场部",
      });

      // 给特定单元格添加批注
      this.addCommentToCell(worksheet, "B2", "年龄需要核实确认");
      this.addCommentToCell(worksheet, "C3", "上海分公司优秀员工");
      this.addCommentToCell(worksheet, "D4", "新入职员工，需要关注");


      // 导出Excel文件
      const buffer = await workbook.xlsx.writeBuffer();
      this.downloadExcel(buffer, "员工信息表.xlsx");
    },
    addCommentToCell(worksheet, cellAddress, commentText) {
        const cell = worksheet.getCell(cellAddress);
        cell.note = commentText;
    },
    downloadExcel(buffer, fileName) {
        const blob = new Blob([buffer], { 
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        });
        
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(url);
    },

    handleSearch() {
      this.formData.pageNum = 1;
      this.getList();
    },
    // 重置查询参数
    resetQueryParams() {
      this.loginTime = [];
      this.formData = {
        pageNum: 1,
        pageSize: 10,
        name: "",
        state: "",
      };
    },
    handleReset() {
      this.resetQueryParams();
      this.getList();
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      dianshangHuishouApi
        .outLinkBackList(this.formData)
        .then((response) => {
          this.cardSecretList = response.rows || [];
          this.total = response.total || 0;
          this.loading = false;
        })
        .catch((error) => {
          this.cardSecretList = [];
          this.total = 0;
          this.loading = false;
        });
    },

    /** 打开创建弹窗 */
    handleCreate() {
      this.dialogVisible = true;
    },

    /** 立即失效 */
    handleInvalidate(row) {
      this.$modal
        .confirm("确认要立即使该秘钥失效吗？")
        .then(() => {
          return cardSecretApi.expire(row.id);
        })
        .then(() => {
          this.$modal.msgSuccess("卡密已失效");
          this.getList();
        });
    },
    // 编辑
    handleEditdate(row) {
      this.$refs.cardSecretModal.open(row);
      this.dialogVisible = true;
    },
    /** 删除 */
    // handleDelete(row) {
    //     this.$modal.confirm('确认要删除该卡密吗？').then(() => {
    //         return cardSecretApi.deleteCardSecret(row.id)
    //     }).then(() => {
    //         this.$modal.msgSuccess('删除成功')
    //         this.getList()
    //     }).catch(error => {
    //         if (error !== 'cancel') {
    //             console.error('删除卡密失败:', error)
    //             this.$modal.msgError('删除卡密失败: ' + (error.message || ''))
    //         }
    //     })
    // },

    /** 复制到剪贴板 */
    copyToClipboard(row) {
      this.$copyText(row.code).then(() =>
        this.$message.success("已复制到剪贴板")
      );
      // if (this.shopInfo.domain) {
      //     const domain = this.shopInfo.domain.split(',')
      //     if (domain.length > 0) {
      //         const link = `http://${domain[0]}/pages/qrLink/qrLink?code=${row.code}&account=${row.account}`;
      //         this.$copyText(link).then(() => this.$message.success('已复制到剪贴板'));
      //     } else {
      //         this.$message.error('暂无地址');
      //     }
      // }
    },

    createXuanhao(row) {
      this.qrCodeShow = true;
      this.qrCodeShow = true;
      let host = "";
      let str = this.shopInfo.otherDomain;
      if (this.shopInfo.otherDomain) {
        if (str.includes("，") || str.includes(",")) {
          host =
            "https://" +
            this.shopInfo.otherDomain.split(/,|，/)[0] +
            "/pages/dianshang/gameList";
        } else {
          host =
            "https://" +
            this.shopInfo.otherDomain +
            "/pages/dianshang/gameList";
        }
      } else {
        host = this.retailDomain["h5"].dictValue + "pages/dianshang/gameList";
      }
      if (row && row.randomStr) {
        this.phoneLink = `${host}?flag=${row.randomStr}`;
      } else {
        this.phoneLink = `${host}`;
      }
      this.$nextTick(() => {
        if (this.qrcode != null) {
          this.qrcode.clear(); // 清除代码
        } else {
        }
        this.qrcode = new QRCode(this.$refs.qrcode, {
          width: 200,
          height: 200,
          correctLevel: QRCode.CorrectLevel.L,
        });
        //生成二维码
        this.qrcode.makeCode(this.phoneLink);
      });
    },
    copy(txt) {
      this.$copyText(txt).then((res) => {
        this.$message.success("已复制到剪切板");
      });
    },
  },
};
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.lines-img {
  margin-top: 2px;
  vertical-align: text-top;
  width: 18px;
  margin-left: 2px;
}

.table_box {
  margin-top: 10px;
}

.search-form-new {
  margin-top: 10px;
}
.mylink {
  margin-right: 10px;
  a {
    color: $primary;
  }
}
</style>